package com.wande.dataplatform.filecollection.mapper;

import cn.hutool.json.JSONUtil;
import com.wande.dataplatform.filecollection.domain.MappingRule;
import com.wande.dataplatform.filecollection.domain.dto.FieldMapping;
import com.wande.dataplatform.filecollection.domain.dto.ValidationRule;
import com.wande.dataplatform.filecollection.domain.vo.MappingRuleVo;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Named;
import org.mapstruct.factory.Mappers;

import java.util.ArrayList;
import java.util.List;

/**
 * MappingRule 到 MappingRuleVo 的映射器
 *
 * @author wande
 */
@Mapper
public interface MappingRuleVoMapper {

    MappingRuleVoMapper INSTANCE = Mappers.getMapper(MappingRuleVoMapper.class);

    @Mapping(target = "fieldMappings", source = "fieldMappings", qualifiedByName = "stringToFieldMappingList")
    @Mapping(target = "validationRules", source = "validationRules", qualifiedByName = "stringToValidationRuleList")
    MappingRuleVo toVo(MappingRule mappingRule);

    @Named("stringToFieldMappingList")
    default List<FieldMapping> stringToFieldMappingList(String json) {
        if (json == null || json.trim().isEmpty()) {
            return new ArrayList<>();
        }
        try {
            return JSONUtil.toList(json, FieldMapping.class);
        } catch (Exception e) {
            return new ArrayList<>();
        }
    }

    @Named("stringToValidationRuleList")
    default List<ValidationRule> stringToValidationRuleList(String json) {
        if (json == null || json.trim().isEmpty()) {
            return new ArrayList<>();
        }
        try {
            return JSONUtil.toList(json, ValidationRule.class);
        } catch (Exception e) {
            return new ArrayList<>();
        }
    }
}